'一个用来管理统一项目的类，负责接受和返回其中的项目'

class_name WeightedTable

var  items: Array[Dictionary] = []#字典数组用来存储每一个能力
var _weight_sum := 0#当前所有元素的总权重

#添加新项目和其权重，如果已有该项目则重新对其权重赋值
func add_item(item, weight: int = 10) -> void:
	for m_item in items:
		if m_item.item == item:
			if weight <= 0:
				remove_item(item)
			else:
				_weight_sum += weight - m_item.weight
				m_item.weight = weight
			return
	items.append({"item": item, "weight": weight})
	_weight_sum += weight
	pass

#改变一个项目的权重
func change_weight(item, change_weight_num: int = 0) -> void:
	for m_item in items:
		if m_item.item == item:
			if (m_item.weight + change_weight_num) < 0:
				remove_item(m_item)
				return
			else:
				_weight_sum += change_weight_num
				m_item.weight += change_weight_num
				return
	add_item(item,change_weight_num)

#移除一个项目
func remove_item(item_in_move) -> void:
	items = items.filter(func(item): return item["item"] != item_in_move)
	_weight_sum = 0
	for item in items:
		_weight_sum += item.weight
	pass

#从中拿去N个项目
func pick_item(number: int = 1):
	if number <= 0:
		return null
	if number > items.size():
		number = items.size()
		
	var chosen_item: Array = []
	
	if number == items.size():
		for item in items:
			chosen_item.append(item.item)
	
	while chosen_item.size() < number:
		var chosen_weight = randi_range(1, _weight_sum)#随机生成一个权重
		var iteration_sum = 0#权重计数器，当权重计数器达到选择权重时，即为要拿去的权重
		for item in items:
			iteration_sum += item.weight
			if chosen_weight <= iteration_sum:
				if !chosen_item.has(item.item):
					chosen_item.append(item.item)
					break

	return chosen_item
